package com.example.ordersystem.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.example.ordersystem.config.AlipayConfig;
import com.example.ordersystem.domain.*;
import com.example.ordersystem.service.CategoryService;
import com.example.ordersystem.service.DishService;
import com.example.ordersystem.service.MerchantService;
import com.example.ordersystem.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Controller
@RequestMapping("/merchant")
public class MerchantController {

    @Autowired
    DishService dishService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    OrderService orderService;

    @Autowired
    MerchantService merchantService;

    @RequestMapping("/homePage")
    public String homePage(HttpServletRequest request) {

        /*分页显示设置,默认每页显示5条菜品,5条分类*/
        HttpSession session = request.getSession();
        session.setAttribute("begin", 0);
        session.setAttribute("end", 4);

        return "/merchants/homePage";
    }

    /**
     * 商家指导手册
     *
     * @return 指导页面
     */
    @RequestMapping("/guide")
    public String guidePage() {
        return "/merchants/guide";
    }

    @RequestMapping("/modifyPassPage")
    public String modifyPassPage() {
        return "/merchants/modifyPass";
    }

    /**
     * 修改商家密码
     *
     * @param mpass   原密码
     * @param newpass 新密码
     * @return
     */
    @RequestMapping("/modifyPass")
    public String modifyPass(HttpServletRequest request, String mpass, String newpass) {

        /*当前商家信息*/
        Merchant merchant = (Merchant) request.getSession().getAttribute("merchant");
        /*判断原始密码是否正确*/
        if (merchant.getPwd().equals(mpass)) {
            /*修改密码*/
            merchantService.modifyPass(merchant.getNum(), newpass);
            /*更新当前商家信息*/
            merchant.setPwd(newpass);
            request.setAttribute("modifySuccess", "密码修改成功");
        } else {
            request.setAttribute("originalPwdError", "原始密码不正确");
        }
        return "forward:/merchant/modifyPassPage";
    }

    /**
     * 查看所有菜品的分页功能
     * @param request
     * @param previous
     * @param next
     * @param all
     * @param nextPage
     * @return
     */
    @RequestMapping("/pageShow")
    public String pageShow(HttpServletRequest request, String previous, String next
            , String all, String nextPage) {

        HttpSession session = request.getSession();

        /*从第begin条留言开始显示*/
        int begin = Integer.parseInt(String.valueOf(session.getAttribute("begin")));

        /*一直显示到第end条留言*/
        int end = Integer.parseInt(String.valueOf(session.getAttribute("end")));

        /*二维留言数组的最大下标*/
        int totalIndex = Integer.parseInt(String.valueOf(session.getAttribute("total"))) - 1;
        int pageSize = 5;

        /*用户点击的是上一页*/
        if (previous != null) {
            /*当前不是第一页*/
            if (begin != 0) {
                /*向上*/
                begin -= pageSize;
                end = begin + (pageSize - 1);
            }
        }
        /*用户点击的是下一页*/
        else if (next != null) {
            /*当前不是最后一页*/
            if (end != totalIndex) {
                /*向下翻页*/
                begin += pageSize;
                end += pageSize;
                if (end > totalIndex) {
                    /*当前页未满5项*/
                    end = totalIndex;
                }
            }
        }
        /*显示所有的*/
        else if (all != null) {
            begin = 0;
            end = 4;
        }

        session.setAttribute("begin", begin);
        session.setAttribute("end", end);
        return "forward:/merchant/".concat(nextPage);
    }

    /**
     * 显示所有菜品的页面
     *
     * @param request 请求
     * @return jsp页面
     */
    @RequestMapping("/dishManagePage")
    public String dishManagePage(HttpServletRequest request) {
        List<DishInfo> dishInfos = dishService.findAllDishInfo();

        if (request.getAttribute("dishInfo") == null) {
            request.setAttribute("dishInfo", dishInfos);
        }
        HttpSession session = request.getSession();
        if (session.getAttribute("begin") == null) {
            session.setAttribute("begin", 0);
        }
        if (session.getAttribute("end") == null) {
            session.setAttribute("end", dishInfos.size() > 5 ? 4 : dishInfos.size() - 1);
        }
        return "/merchants/allDish";
    }

    /**
     * 根据关键字查询菜品
     *
     * @param request      请求
     * @param keyword      关键字
     * @param previousPage 发出请求的页面 查询出来的菜品，也需要分页显示，previousPage也是即将跳转的页面，有利于pageShow。
     * @return
     */
    @RequestMapping("/selectDishInfoByKeyword")
    public String selectDishByKeyword(HttpServletRequest request, String keyword, String previousPage) {

        /*从第一个结果开始显示*/
        request.getSession().setAttribute("begin", 0);

        /*根据关键字对dishes进行过滤*/
        List<DishInfo> dishes = dishService.selectDishInfoByKeyword(keyword);

        request.setAttribute("dishInfo", dishes);

        /*分页显示*/
        request.getSession().setAttribute("begin", 0);

        /*每页5条结果，分页显示*/
        request.getSession().setAttribute("end", dishes.size() > 5 ? 4 : dishes.size() - 1);

        /*previousPage代表发出请求的页面，也是接下来要转向的页面，是同一个页面*/
        return "forward:/merchant/".concat(previousPage);
    }

    /**
     * 删除或者编辑菜品
     *
     * @param request 请求
     * @param num     菜品编号
     * @return 删除或编辑完成后，返回所有商品页面
     */
    @RequestMapping("/editOrDeleteDish")
    public String editOrDeleteDish(HttpServletRequest request, String num) {

        /*用户选择编辑菜品*/
        if (request.getParameter("edit") != null) {
            /*查询该商品的具体信息*/
            request.setAttribute("dish", dishService.findDishByNum(num));
            return "forward:/merchant/editDish";
        }
        /*用户选择删除菜品*/
        else if (request.getParameter("delete") != null) {
            dishService.deleteDish(num);
            return "forward:/merchant/dishManagePage";
        }
        return "forward:/merchant/dishManagePage";
    }

    /**
     * 编辑菜品信息页面
     *
     * @param request 请求
     * @return 编辑完成后，返回到显示所有菜品信息的页面
     */
    @RequestMapping("/editDish")
    public String editDish(HttpServletRequest request) {
        request.setAttribute("categories", categoryService.findAllCategoryNames());
        return "/merchants/editDish";
    }

    /**
     * 添加菜品的jsp页面
     *
     * @param request 请求
     * @return 添加菜品的页面
     */
    @RequestMapping("/addDishPage")
    public String addDish(HttpServletRequest request) {
        request.setAttribute("categories", categoryService.findAllCategoryNames());
        return "/merchants/addDish";
    }

    /**
     * 添加菜品的第一步:上传菜品图片
     */
    @RequestMapping("/uploadDishPicture")
    public String uploadDishPicture(MultipartFile file, HttpServletRequest request) throws IOException {

        request.setCharacterEncoding("utf-8");
        if (file.isEmpty()) {
            request.setAttribute("msg", "请选择文件");
            return "forward:/merchant/addDishPage";
        }
        //存储图片的路径
        Dish dish = new Dish();
        dish.setPicture(upload(file,request, Dish.PICTURE_PATH));
        request.getSession().setAttribute("add", dish);
        return "forward:/merchant/addDishPage";
    }

    /**
     * 实现真正的上传功能
     *
     * @param file     待上传的文件
     * @param filePath 上传到本地磁盘路径
     * @return 图片上传完成后, 返回新的文件名
     * @throws IOException 文件图片大小限制
     */
    private String upload(MultipartFile file, HttpServletRequest request,String filePath) throws IOException {

        /*获取项目运行时,评论中图片的存储路径*/
        String realPath = request.getServletContext().getRealPath(filePath);
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀名称
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //新图片名称
        String fileName = getPictureNum().concat(suffix);
        //上传图片
//        File newFile = new File(filePath.concat(File.separator).concat(fileName));
        File newFile = new File(realPath, Objects.requireNonNull(fileName));

        /*将接收到的文件传输到给定的目标文件*/
        if (!newFile.exists()) {
            file.transferTo(newFile);
        }
        return fileName;
    }

    /**
     * 根据时间戳,为图片生成编号
     *
     * @return 编号
     */
    private String getPictureNum() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        return sdf.format(new Date());
    }

    /**
     * 添加菜品的第二步:菜品的详细信息
     *
     * @param request     请求
     * @param categoryNum 菜品分类
     * @param name        菜品名称
     * @param price       菜品价格
     * @param description 菜品描述
     * @return 添加成功后，返回所有菜品页面
     */
    @RequestMapping("addDishDetail")
    public String addDishDetail(HttpServletRequest request, String categoryNum, String name
            , String price, String description) {
        /*待添加的菜品*/
        Dish add = (Dish) request.getSession().getAttribute("add");
        /*菜品信息添加到数据库*/
        dishService.addDish(add, categoryNum, name, price, description);
        /*会话中移除待添加的菜品*/
        request.getSession().removeAttribute("add");
        return "forward:/merchant/dishManagePage";
    }

    /**
     * 查询所有的分类信息，并转向jsp页面
     *
     * @param request 请求
     * @return 显示所有分类信息的页面
     */
    @RequestMapping("/categoryPage")
    public String categoryPage(HttpServletRequest request) {

        List<Category> categories = categoryService.findAllCategories();
        request.setAttribute("categories", categories);
        return "/merchants/category";
    }

    /**
     * 添加菜品分类的页面
     *
     * @return
     */
    @RequestMapping("/addCategoryPage")
    public String addCategoryPage() {
        return "/merchants/addCategory";
    }

    @RequestMapping("/addCategory")
    public String addCategory(HttpServletRequest request,String name){
        categoryService.addCategory(name);
        request.setAttribute("addSuccess","添加分类成功");
        return "forward:/merchant/addCategoryPage";
    }

    @RequestMapping("/selectOrder")
    public String selectOrder(HttpServletRequest request, String begin, String end) {

        request.setAttribute("orders", orderService.findBetweenAnd(begin, end));
        return "/merchants/allOrder";
    }

    @RequestMapping("/deleteCategory")
    public String deleteCategory(HttpServletRequest request,String categoryNum){
        /*根据分类编号查询菜品*/
        List<Dish> dishes = dishService.findByCategoryNum(categoryNum);
        /*分类中仍包含菜品*/
        if (dishes!=null && dishes.size()>0){
            request.setAttribute("error","无法删除分类,分类中仍包含菜品");
        }else {/*分类是空的*/
            categoryService.deleteByNum(categoryNum);
            request.setAttribute("success","删除成功");
        }

        return "forward:/merchant/categoryPage";
    }

    /**
     * 显示所有订单的页面
     *
     * @param request 请求
     * @return 从数据库中查询所有的订单信息，在jsp页面显示
     */
    @RequestMapping("/allOrder")
    public String allOrder(HttpServletRequest request) {
        request.setAttribute("orders", orderService.findAllOrder());
        return "/merchants/allOrder";
    }

    /**
     * 显示店面管理页面
     *
     * @param request 请求所有店面信息
     * @return
     */
    @RequestMapping("/roomAddress")
    public String roomAddress(HttpServletRequest request){
        request.setAttribute("roomaddress",merchantService.findAllRoom());
        return "merchants/roomAddress";
    }

    /**
     * 删除店面
     * @param request
     * @param addressName 店面名称
     * @return
     */
    @RequestMapping("/deleteAddress")
    public String deleteAddress(HttpServletRequest request,String addressName){
        merchantService.deleteAddress(addressName);
        request.setAttribute("deletesuccess","删除成功");
        return "forward:/merchant/roomAddress";
    }

    @RequestMapping("/addAddressPage")
    public String addAddressPage(HttpServletRequest request){
        return "merchants/addAddress";
    }

    @RequestMapping("/addAddress")
    public String addAddress(HttpServletRequest request,String name,String address,String lng,String lat){
        merchantService.addAddress(name,address,lng,lat);
        request.setAttribute("addAddrSuccess","添加店面成功");
        return "forward:/merchant/addAddressPage";
    }

    private void outPut(String msg) {
        System.out.println("********************");
        System.out.println(msg);
        System.out.println("********************");
    }

    /**
     * 退款
     *
     * @param request 请求
     * @return 是否退款成功
     * @throws AlipayApiException 退款异常
     */
    @RequestMapping("/refund")
    public String refund(HttpServletRequest request, String orderNum, String amount) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        String out_trade_no = orderNum;
        //支付宝交易号
        String trade_no = "";
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        String refund_amount = amount;
        //退款的原因说明
        String refund_reason = "";
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
        String out_request_no = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"trade_no\":\"" + trade_no + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"refund_reason\":\"" + refund_reason + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}");

        AlipayTradeRefundResponse response = alipayClient.execute(alipayRequest);
        outPut(response.getBody());
        if (response.isSuccess()) {
            /*在数据库中更新订单状态*/
            orderService.updateStatusByNum(orderNum, Order.TRADE_STATUS.get(Order.CLOSED));
            request.setAttribute("success", "退款成功");
        }
        return "forward:/merchant/allOrder";
    }

}
